package com.taotao.manage.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.taotao.manage.mapper.ContentCategoryMapper;
import com.taotao.manage.pojo.ContentCategory;

@Service
public class ContentCategoryService extends BaseService<ContentCategory>{
	
	@Autowired
	ContentCategoryMapper contentCategoryMapper;
	
	public ContentCategory addContentCategory(Long parentId, String name) {
		ContentCategory record = new ContentCategory();
		record.setParentId(parentId);
		record.setName(name);
		record.setStatus(1);
		record.setIsParent(false);
		Boolean flag = super.save(record);
		if(flag){
			ContentCategory parent =  new ContentCategory();
			parent.setId(parentId);
			parent.setIsParent(true);
			Integer count = super.count(parent);
			if(count == 0){
				flag = this.update(parent);
			}
		}
		if(flag)
			return record;
			return null;
	}
	
	//删除节点, 1)递归删除其全部子节点, 2)检查其父节点是否还有其他子节点, 如果没有更新父节点的isParent属性为false
	public boolean deleteContentCategory(Long id,Long parentId) {
		// 2)检查其父节点是否还有其他子节点, 如果没有更新父节点的isParent属性为false
		ContentCategory record = new ContentCategory();
		record.setParentId(parentId);
		Integer count = super.count(record);
		Boolean flag = true;
		if(count==1){
			ContentCategory parent = new ContentCategory();
			parent.setId(parentId);
			parent.setIsParent(false);
			flag = super.update(parent);
		}
		// 1)递归删除其全部子节点
		if(flag){
			List<Object> ids = new ArrayList<Object>();
			ids.add(id);
			this.queryChildren(id, ids);
			Integer deleteByIds = super.deleteByIds("id", ContentCategory.class, ids);
			if(deleteByIds==0){
				flag = false;
			}
		}
		return flag;
	}
	
	/**
	 * 根据parentId递归查询所有的子节点, 将子节点的id存放到list集合
	 * @param parentId
	 * @param ids
	 */
	public void queryChildren(Long parentId, List<Object> ids){
		ContentCategory record = new ContentCategory();
		record.setParentId(parentId);
		List<ContentCategory> list = super.queryByRecord(record);
		
		for (ContentCategory c : list) {
			ids.add(c.getId());
			queryChildren(c.getId(), ids);
		}
	}
		
}







